<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #canvas {
      box-shadow: 2px 4px 6px #eee;
    }
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
<script src="../script/utils.js"></script>
<script src="../components/Box.js"></script> 
<script>
  const canvas = document.getElementById('canvas')
  const ctx = canvas.getContext('2d')
  
  const W = canvas.width = 800
  const H = canvas.height = 600
  
  let mouse = C.getOffset(canvas)
  let boxes = [], g = 0.02, activeBox = createBox()

  function createBox() {
    const box = new Box({
      x: C.rp([0, W]),
      w: C.rp([20, 55]),
      h: C.rp([20, 55]),
      fillStyle: C.createColor()
    })
    boxes.push(box)
    return box
  }

  function drawFrame() {
    window.requestAnimationFrame(drawFrame)
    ctx.clearRect(0, 0, W, H)

    activeBox.vy += g
    activeBox.y += activeBox.vy
    if (activeBox.y + activeBox.h >= H) {
      activeBox.y = H - activeBox.h
      activeBox = createBox()
    }
    boxes.forEach(item => {
      if (item !== activeBox && C.rectDuang(item, activeBox)) {
        activeBox.y = item.y - activeBox.h
        activeBox = createBox()
      }
      item.render(ctx)
    })
  }
  drawFrame()
</script>
</html>